package main

import (
	"flag"
	"fmt"

	"github.com/fsnotify/fsnotify"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"

	"mychat/internal/common/logger"
	"mychat/internal/conf"
	"mychat/internal/server"
)

var confFile string

func init() {
	flag.StringVar(&confFile, "conf", "./configs/dev.yaml", "config file path, eg -conf your_conf.yaml")
}

func main() {
	flag.Parse()

	bs := initAppConfig()
	lg := logger.NewStdLogger(bs.App.Logger)
	app := server.NewServer(bs, lg)
	gin.SetMode(bs.App.GinMode)

	err := app.Run()
	if err != nil {
		panic(err)
	}
}

func initAppConfig() *conf.Bootstrap {
	if confFile != "" {
		viper.SetConfigFile(confFile)
	} else {
		panic("config file is required")
	}

	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("viper reader config file err: %v", err))
	}

	var bs conf.Bootstrap
	err = viper.Unmarshal(&bs)
	if err != nil {
		panic(err)
	}

	viper.WatchConfig()

	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Printf("config file changed: %s\n", in.Name)
	})

	return &bs
}
